package com.garbagecan.cachestudy.oscache.disk;

import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.opensymphony.oscache.base.Cache;
import com.opensymphony.oscache.base.NeedsRefreshException;
import com.opensymphony.oscache.general.GeneralCacheAdministrator;

public class DiskCacheExample {
	
	private static Log log = LogFactory.getLog(DiskCacheExample.class);	
	
	public static void main(String[] args) throws Exception {
		DiskCacheExample dce = new DiskCacheExample();
		dce.test();
		dce.testWithGroup();
	}
	
	private void test() throws Exception {
		Cache cache = getCache();
		String myKey = "myKey";
		String myValue = "myValue";
		String myTmpKey = null;
		String myTmpValue = null;
		try {
			for( int i = 0 ; i < 10 ; i++) {
				myTmpKey = myKey + i;
				myTmpValue = myValue + i;
				cache.putInCache(myTmpKey, myTmpValue);
				log.info(cache.getFromCache(myTmpKey));
			}
		} catch (NeedsRefreshException ex) {
			// log.error("The cache does not exist!");
			ex.printStackTrace();
			cache.cancelUpdate(myTmpKey);
		}
	}
	
	private void testWithGroup() throws Exception {
		Cache cache = getCache();
		String myKey = "myKey";
		String myValue = "myValue";
		String myTmpKey = null;
		String myTmpValue = null;
		String[] myGroup = {"mygroup1", "mygroup2"};
		try {
			for( int i = 0 ; i < 10 ; i++) {
				myTmpKey = myKey + i;
				myTmpValue = myValue + i;
				cache.putInCache(myTmpKey, myTmpValue, myGroup);
				log.info(cache.getFromCache(myTmpKey));
			}
		} catch (NeedsRefreshException ex) {
			// log.error("The cache does not exist!");
			ex.printStackTrace();
			cache.cancelUpdate(myTmpKey);
		}
	}
	
	private Cache getCache() {
		Properties prop = new Properties();
		prop.put("cache.memory", "true");
		prop.put("cache.persistence.overflow.only", "true");
		//prop.put("cache.path", "c:\\cache");
		prop.put("cache.path", "/home/fkong/temp/abc");
		prop.put("cache.capacity", "1");
		prop.put("cache.unlimited.disk", "true");
		prop.put("cache.blocking", "true");
		prop.put("cache.persistence.class", "com.opensymphony.oscache.plugins.diskpersistence.DiskPersistenceListener");
		prop.put("cache.event.listeners", "com.opensymphony.oscache.extra.CacheMapAccessEventListenerImpl");
		GeneralCacheAdministrator cacheAdmin = new GeneralCacheAdministrator(prop);
		return cacheAdmin.getCache();
	}
}
